//
//  LogViewController.m
//  SSC
//
//  Created by 红沙尘 on 17/6/6.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "LogViewController.h"
#import "SQLITE.h"
#import "HSCLogCell.h"
#import "HSCLog.h"

@interface LogViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    __weak IBOutlet UITableView *logTableView;
    
    NSArray *logArray;
}
@end

@implementation LogViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    logArray = [[SQLITE standardSqlite] selectSQLFromtable:@"log"
                                                elementKey:@"id"
                                              elementValue:@""
                                                     limit:0
                                                    offset:0
                                                     order:DESC];
    logTableView.tableFooterView = [UIView new];
    
    logTableView.rowHeight = UITableViewAutomaticDimension;
    logTableView.estimatedRowHeight = 50;
    
    [logTableView registerNib:[UINib nibWithNibName:@"HSCLogCell" bundle:nil]
       forCellReuseIdentifier:@"HSCLogCell"];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(0, 0, 50, 44);
    [btn setTitle:@"关闭" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return logArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HSCLogCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HSCLogCell"];
    
    [cell loadWithDict:logArray[indexPath.section]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = [HSCLog dataTOjsonString:logArray[indexPath.section]];
    
    NSString *msg = @"数据已经复制到剪贴板";
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
                                                                             message:msg
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

@end
